package com.study.interceptor;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author zhuzi
 * 2024/12/2 9:14
 */
@Slf4j
@Component
public class SignsInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        final String method = request.getMethod();
        final String url = request.getRequestURI();
        if (request instanceof ContentCachingRequestWrapper) {
            ContentCachingRequestWrapper wrapper = (ContentCachingRequestWrapper) request;
            // 你可以在这里读取请求体，因为它已经被缓存
            byte[] body = wrapper.getContentAsByteArray();
            // 处理请求体

            Map<String, String[]> parameterMap = request.getParameterMap();

            System.out.println(StringUtils.center("sign拦截器", 51, "*"));
            System.out.println(method);
            System.out.println(url);
            System.out.println(new String(body));

            System.out.println("map");
            System.out.println(JSON.toJSONString(parameterMap));
        }


        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
